﻿using System.Collections.Generic;
using System;
using UnityEngine;
using Yunchang;
using System.Collections;

namespace AutoChess
{
    class AutoChessFieldCtr : IVisualData<AutoChessFieldCtr, AutoChessFieldViewCtr>
    {
        public AutoChessMapMgr AutoChessMapMgr;
        public AutoChessPlayerCtr entityMap;
        public AutoChessFieldViewCtr GameModeAutoChessFieldRenderer;
        private List<OpretionMsg> opretionActions = new List<OpretionMsg>();
        public FightEntityCtr fightCtr;

        public IEnumerator SwitchWatchingPlayer(long playerId)
        {
            LoadingPanel.Instance.ShowCloudMask();
           
            ClearMsgAction();//清除当前的消息
            entityMap.CurrentPlayer.LeaveBattleField();
            AutoChessManager.Ins.cacheData.SwitchFieldPlayer(playerId);
            var entity = entityMap.CreatePlayerData(AutoChessManager.Ins.cacheData.CurPlayerData);
            entityMap.GeneratePlayerEntity(entity);

            //切换玩家后 如果是战斗状态 , 需要重新刷新战斗状态 显示战斗结果. 调整阶段只需要将当前创建就可以了
            EventManager.TriggerEvent<long>(CommonEvent.SWITCH_AUTO_CHESS_PLAYER, playerId);

            if (AutoChessManager.Ins.SceneCmpt.IsNeedLoadScene())
            {
                yield return new WaitForSeconds(0.5f);
            }

            AutoChessManager.Ins.SceneCmpt.LoadCurPlayerScene();

            while (!AutoChessManager.Ins.SceneCmpt.IsSceneLoadComplete)
            {
                yield return null;
            }

            if (AutoChessManager.Ins.GetCurrentStateType() != AutoChessModeState.ShowFightState)
            {
                LoadingPanel.Instance.HiedCloudMask(0.6f);
            }

            yield return null;
            entityMap.CurrentPlayer.RefreshHeroNumberState();
        }

        private void ClearMsgAction()
        {
            opretionActions.Clear();
        }

        #region 推入操作指令、GameAction、演算等

        public void InitGameField()
        {
            AutoChessMapMgr = AutoChessMapMgr.Ins;
            entityMap = AutoChessPlayerCtr.Ins;
            fightCtr = new FightEntityCtr();
            EventManager.AddEventListener<OpretionMsg>(CommonEvent.PUSH_GAMEFIELD_MSG, OnPushGameFieldMsg);
            EventManager.AddEventListener<OpretionMsg[]>(CommonEvent.PUSH_GAMEFIELD_MSG_ARR, OnPushGameFieldMsgArr);
            EventManager.AddEventListener<GridType>(CommonEvent.ON_GAMEFIELD_CHESS_UPDATE, OnChessUpdate);
        }

        public void Release()
        {
            EventManager.RemoveEventListener<OpretionMsg>(CommonEvent.PUSH_GAMEFIELD_MSG, OnPushGameFieldMsg);
            EventManager.RemoveEventListener<OpretionMsg[]>(CommonEvent.PUSH_GAMEFIELD_MSG_ARR, OnPushGameFieldMsgArr);
            EventManager.RemoveEventListener<GridType>(CommonEvent.ON_GAMEFIELD_CHESS_UPDATE, OnChessUpdate);
            DisconnectRenderer();
            AutoChessMapMgr.Release();
            entityMap.Release();
            fightCtr.Release();
        }

        public void OnChessUpdate(GridType gridType)
        {
            entityMap.CurrentPlayer.RefreshHeroNumberState();
        }

        public void GenerateFieldUnit()
        {
            AutoChessMapMgr.InitMap();
            //AutoChessFieldViewCtr.Ins.RefreshGameFieldMapGrid();//创建英雄前线将格子渲染器创建 这里代码规范性有待调整
            AutoChessManager.Ins.cacheData.SwitchFieldPlayer(StaticData.playerData.playerId);
            GenerateTargetPlayerEntity(AutoChessManager.Ins.cacheData.CurPlayerData);
        }

        // 进入游戏生成自己 生成一个目标的实体
        public void GenerateTargetPlayerEntity(ACPlayerData playerData)
        {
            var entity = entityMap.CreatePlayerData(playerData);
            entityMap.GeneratePlayerEntity(entity);
        }

        private void OnPushGameFieldMsg(OpretionMsg fieldMsg)
        {
            opretionActions.Add(fieldMsg);
        }

        private void OnPushGameFieldMsgArr(OpretionMsg[] fieldMsgArr)
        {
            opretionActions.AddRange(fieldMsgArr);
        }

        public void Tick()
        {
            if (opretionActions.Count > 0)
            {
                for (int idx = 0; idx < opretionActions.Count; idx++)
                {
                    RunAction(opretionActions[idx]);
                }
                opretionActions.Clear();
            }
        }

        private void RunAction(OpretionMsg msg)
        {
            if (msg.opretionType == OpretionType.Grid)
            {
                AutoChessMapMgr.RunAction(msg as GridOpretionMsg);
            }
            else if (msg.opretionType == OpretionType.Hero)
            {
                AutoChessMapMgr.RunAction(msg as HeroOpretionMsg);
            }
            else if (msg.opretionType == OpretionType.Control)
            {
                RunControlMsg(msg as GameControlOperationMsg);
            }
        }

        private void RunControlMsg(GameControlOperationMsg msg)
        {
            if (msg is ClickDownUnitMsg)
            {
                var data = msg as ClickDownUnitMsg;

                // 更新点击的格子效果
                if (data.selectedUnit == null || data.selectedUnit.heroUnit == null)
                    OnPushGameFieldMsg(GridOpretionMsg.NewSelectGridMsg(null));
                else
                    OnPushGameFieldMsg(GridOpretionMsg.NewSelectGridMsg(data.selectedUnit));
            }
            else if (msg is ClickUpUnitMsg)
            {
                var data = msg as ClickUpUnitMsg;
                bool hasValidControlMsg = false;

                if (data.lastSelectedUnit != null && data.curSelectedUnit != null)
                {
                    var lastACGrid = data.lastSelectedUnit;
                    ACHero lastHeroUnit = null;
                    var curACGrid = data.curSelectedUnit;
                    ACHero curHeroUnit = null;
                    if (lastACGrid.heroUnit != null)
                        lastHeroUnit = lastACGrid.heroUnit;
                    if (curACGrid.heroUnit != null)
                        curHeroUnit = curACGrid.heroUnit;

                    // 拖拽
                    if (lastACGrid != curACGrid)
                    {
                        // 只能操作自己的格子
                        if(AutoChessPlayerCtr.Ins.CurrentPlayer.IsSelfPlayer)
                        {
                            // 战斗的时候不能操控战斗场的格子
                            if (
                            (lastACGrid.GridType == GridType.FightGrid || curACGrid.GridType == GridType.FightGrid)
                            &&
                            AutoChessManager.Ins.cacheData.ServerDataState != ProtoBuf.Message.AutoChessStateType.AUTO_CHESS_STATE_ADJUST
                            )
                            {
                                // Do Nothing(hasValidControlMsg = false;)
                            }
                            // 移动
                            else if (lastHeroUnit != null && curHeroUnit == null)
                            {
                                if (curACGrid.GridType == GridType.FightGrid || curACGrid.GridType == GridType.PreChooseGrid)
                                {
                                    if (lastACGrid.GridType == GridType.ShopGrid)
                                    {
                                        AutoChessManager.Ins.SendBuyChess(lastACGrid.ServerIndex, curACGrid.ServerIndex);
                                        hasValidControlMsg = true;
                                    }
                                    else
                                    {
                                        AutoChessManager.Ins.SendCSAutoChessMoveChess(lastACGrid.ServerIndex, curACGrid.ServerIndex);
                                        hasValidControlMsg = true;
                                    }
                                }
                            }
                            // 替换
                            else if (lastHeroUnit != null && curHeroUnit != null)
                            {
                                if ((lastACGrid.GridType == GridType.FightGrid || lastACGrid.GridType == GridType.PreChooseGrid)
                                    &&
                                    (curACGrid.GridType == GridType.FightGrid || curACGrid.GridType == GridType.PreChooseGrid))
                                {
                                    AutoChessManager.Ins.SendCSAutoChessMoveChess(lastACGrid.ServerIndex, curACGrid.ServerIndex);
                                    hasValidControlMsg = true;
                                }
                            }
                        }
                    }
                    // 点击
                    else
                    {
                        if (lastHeroUnit != null)
                        {
                            if (data.lastSelectedUnit.GridType == GridType.ShopGrid && AutoChessPlayerCtr.Ins.CurrentPlayer.IsSelfPlayer)
                            {
                                UtilityHelper.PlayUIAudio("AC_buyChess");
                                AutoChessManager.Ins.SendBuyChess(data.lastSelectedUnit.ServerIndex);
                                hasValidControlMsg = true;
                            }
                            else
                            {
                               // if(!/*lastHeroUnit.isDeathHide*/ )
                               if(!lastHeroUnit.Attr.GetAtrribute<bool>(ActorActionAttrDef.ACHero_Death_Hide))
                                    EventManager.TriggerEvent(CommonEvent.ON_AC_CHECK_CHESS_INFO, lastHeroUnit.ChessID);
                            }
                        }
                    }
                }
                if (!hasValidControlMsg)
                {
                    AutoChessFieldViewCtr.Ins.InputCtr.ResetPreviewControlData();
                }
            }
        }

        public void AutoUpgradeStarMsg(ACGrid toGrid)
        {
            if (!AutoChessPlayerCtr.Ins.CurrentPlayer.IsSelfPlayer
                || toGrid == null
                || toGrid.heroUnit == null
                || toGrid.GridType != GridType.FightGrid)
                return;

            var chessTable = Table.Blo.AutoChessBlo.GetChessTable(toGrid.heroUnit.ChessID);
            if (chessTable.star >= 3)
                return;

            int sameChessIdNum = 0;
            foreach (var item in AutoChessPlayerCtr.Ins.CurrentPlayer.HeroUnits)
            {
                if (item.MapGrid != null && item.MapGrid.GridType == GridType.FightGrid && item.ChessID == toGrid.heroUnit.ChessID)
                {
                    
                    ++sameChessIdNum;
                    if (sameChessIdNum >= 3)
                    {
                        AutoChessManager.Ins.SendUpgradeStar(toGrid.ServerIndex);
                        break;
                    }
                }
            }
        }
        #endregion


        #region 渲染器
        public void ConnectRenderer(AutoChessFieldViewCtr renderer)
        {
            if (GameModeAutoChessFieldRenderer != null)
                return;

            GameModeAutoChessFieldRenderer = renderer;
            GameModeAutoChessFieldRenderer.OnConnect(this);
            Debug.Log(string.Format("{0} connect renderer.", this.ToString()));
        }

        public void DisconnectRenderer()
        {
            if (GameModeAutoChessFieldRenderer != null)
            {
                GameModeAutoChessFieldRenderer.OnDisconnect();
                Debug.Log(string.Format("{0} disconnect renderer.", this.ToString()));
            }
        }
        #endregion
    }
}
